#!/bin/bash

set -o errexit
set -o xtrace

test_dir=$(realpath $(dirname $0))
. ${test_dir}/../functions

check_cr_config() {
    local cluster="$1"

    # apply cr config
    apply_cluster $test_dir/conf/$cluster.yml

    # check if at least 1 Pod started
    wait_for_running $cluster 1 "false"

    # check if statefulset created with expected config
    compare_kubectl statefulset/$cluster

    # change resources
    cat_config $test_dir/conf/$cluster.yml \
        | sed -e 's/300m/600m/' \
        | sed -e 's/500M/1G/' \
        | sed -e 's/0.5G/1G/' \
        | kubectl_bin apply -f-
    sleep 10

    # check if statefulset was updated with expected config
    compare_kubectl statefulset/$cluster "-increased"

    # delete cluster
    kubectl_bin delete \
        -f $test_dir/conf/$cluster.yml
}

no_storage() {
    local cluster="no-storage-rs0"

    # apply cr config
    apply_cluster $test_dir/conf/$cluster.yml
    sleep 20

    kubectl_bin logs $(get_operator_pod) \
        | grep "volumeSpec should be specified"

    # delete cluster
    kubectl_bin delete \
        -f $test_dir/conf/$cluster.yml
}

main() {
    create_namespace $namespace
    deploy_operator
    kubectl_bin apply -f $conf_dir/secrets.yml

    desc 'check if possible to create cluster without CPU/Memory limits'
    check_cr_config "no-limits-rs0"

    desc 'check if possible to create cluster without CPU/Memory requests'
    check_cr_config "no-requests-rs0"

    desc 'check if possible to create cluster without CPU/Memory requests and limits'
    check_cr_config "no-requests-no-limits-rs0"

    desc 'check if possible to create cluster without storage size'
    no_storage

    destroy $namespace
}

main
